# coding: utf-8

module ApplicationHelper

  def can?(role)
    current_user && current_user.role?(role)
  end

  def link_to_new_comment(document)
    link_to t('comments.add_new_comment'), new_comment_path(:document_id => document.id),
        :remote => true, :class => "btn primary show-loader"
  end

  def link_to_delete_comment(comment)
    link_to image_tag("icons/delete.png"), comment_path(comment),
            :method => :delete, :remote => true, :class => "delete"
  end

  def link_to_document(document)
    case document.source
      when Article     then documents_article_path(document.source)
      when Publication then documents_publication_path(document.source)
      when News        then documents_news_path(document.source)
      when Conference  then documents_conference_path(document.source)
    end
  end

  def entry(content, options={})
    length = options[:length] ||= 400
    content.gsub(/<\/?.*?>/, "").truncate(length).html_safe
  end

  def inputs_for_document_tags(document, &block)
    document.tags.each do |tag|
      field = text_field_tag "tags[]", tag.label, :id => "tag_#{tag.id}"
      link = link_to "", "#", :class => "delete"
      block.call field + link
    end
  end

  def links_for_tags(tags, &block)
    tags.each{|tag| block.call link_to(tag.label, list_documents_by_tag_path(tag.label))}
  end

  def tags_for_select(tags)
    tags.collect{|tag| tag.label}
  end

  def tag_cloud(tags, &block)
    map = {}
    tags.each do |tag|
      if map[tag.label].present?
        map[tag.label] += 1
      else
        map[tag.label] = 1
      end
    end
    map.each{|label, count| block.call link_to label, list_documents_by_tag_path(label)}
  end

  def link_for_change_rating(target, effect)
    type = target.class.to_s.downcase
    url       = (effect == :up) ? rating_up_path(type, target.id) : rating_down_path(type, target.id)
    css_class = (effect == :up) ? "good-mark" : "bad-mark"
    link_to "", url, :method => :put, :remote => true, :class => css_class
  end

  def html_tag_for_rating(target)
    if target.rating == 0
      value = "-"
    else
      value = target.rating > 0 ? "+#{target.rating}" : target.rating
      css_class = target.rating > 0 ? "green" : "red"
    end

    content_tag(:span, value, :id => dom_id(target), :class => css_class)
  end

  def ajax_loader
    content_tag(:div, content_tag(:div, nil, :class => "loader-image"), :class => "ajax-loader")
  end

  def durations_for_select
    [
        [t('time_period_this_day'),          Time.now.utc.midnight            ],
        [t('time_period_this_week'),         Time.now.utc.midnight - 1.week   ],
        [t('time_period_this_month'),        Time.now.utc.midnight - 1.month  ],
        [t('time_period_this_three_months'), Time.now.utc.midnight - 3.month  ],
        [t('time_period_this_six_months'),   Time.now.utc.midnight - 6.month  ],
        [t('time_period_this_year'),         Time.now.utc.midnight - 1.year   ]
    ]
  end
end
